<script setup lang="ts">
import type { UploadChangeParam, UploadFile } from 'ant-design-vue'
import { Attachments } from 'ant-design-x-vue'
import { reactive, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useGlobalStore } from '@/stores/global'

// 全局存储
const globalStore = useGlobalStore()
const { bindAttachList } = storeToRefs(globalStore)

// 上一次选择文件时队列
let $prevFileList = undefined

// 状态参数
const state = reactive({
  // 上传锁，防止从组件内部上传
  uploadLock: true,
})

// 组件
const attachmentsRef = ref()

// 选择文件
const handleChange = (info: UploadChangeParam<UploadFile>) => {
  if (info.fileList.findIndex((item) => item.uid === info.file.uid) > -1) {
    // 新增，只有解锁后才会上传
    if (!state.uploadLock) {
      bindAttachList.value = info.fileList
      onUploadFile(info.file)
    } else {
      bindAttachList.value = [...$prevFileList]
    }
  } else {
    // 删除
    bindAttachList.value = info.fileList
    onDeleteFile(info.file)
  }
  state.uploadLock = true
  $prevFileList = [...bindAttachList.value]
}

// 上传文件
const onUploadFile = async (file: UploadFile) => {
  const info = bindAttachList.value.find((item) => item.uid === file.uid)
  info.status = 'uploading'
  const reader = new FileReader()

  reader.onload = (e) => {
    info.status = 'done'
    info.url = e.target.result as string
  }

  reader.onerror = (error) => {
    info.status = 'error'
    info.response = error
  }

  reader.readAsDataURL(file as any)
}

// 删除文件
const onDeleteFile = async (file: UploadFile) => {
  bindAttachList.value = bindAttachList.value.filter((item) => item.uid !== file.uid)
}

defineExpose({
  // 外部上传
  upload: (file: File) => {
    state.uploadLock = false
    attachmentsRef.value.upload(file)
  },
})
</script>

<template>
  <div class="attach" :class="{ on: bindAttachList.length > 0 }">
    <Attachments
      ref="attachmentsRef"
      :beforeUpload="() => false"
      :items="bindAttachList"
      @change="handleChange"
    />
  </div>
</template>

<style lang="scss" scoped>
.attach {
  display: none;
  overflow: hidden;

  :deep(.ant-attachment-list-card-text) {
    color: rgba(255, 255, 255, 0.85) !important;
  }
  :deep(.ant-attachment-list > .ant-upload-wrapper) {
    display: none;
  }

  &.on {
    display: block;
  }
}
</style>
